/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.lenovo.nova.util.network;

import android.annotation.TargetApi;
import android.os.Build;
import android.os.Process;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

/**

 */
public abstract class AdvanceInvoke<T> extends Thread {
	/** The queue of requests to service. */
	private final BlockingQueue<T> mQueue;
	/** Used for telling us to die. */
	private volatile boolean mQuit = false;
	private boolean isStart;

	/**
	 * Creates a new network dispatcher thread. You must call {@link #start()}
	 * in order to begin processing.
	 *
     */
	public AdvanceInvoke() {
		mQueue = new PriorityBlockingQueue<T>();
	}

	public void add(T cmd){
		mQueue.add(cmd);
	}
	
	/**
	 * Forces this dispatcher to quit immediately. If any requests are still in
	 * the queue, they are not guaranteed to be processed.
	 */
	public void quit() {
		mQuit = true;
		interrupt();
		isStart = false;
	}

	@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
	private void addTrafficStatsTag(T request) {
		// Tag the request (if API >= 14)
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
			// TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
		}
	}

	@Override
	public synchronized void start() {
		super.start();
		isStart = true;
	}
	@Override
	public void run() {
		Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
		while (true) {
            T request;
			try {
				// Take a request from the queue.
				request = mQueue.take();
			} catch (InterruptedException e) {
				// We may have been interrupted because it was time to quit.
				if (mQuit) {
					return;
				}
				continue;
			}

			try {
				// Perform the network request.
                onExecute(request);
				
				System.out.println("execute cmd");
			} catch (Exception e) {

			}
		}
	}

    protected abstract void onExecute(T request);

    public boolean isStart() {
		return isStart;
	}
}
